package pub.gll.onepeas.libbase.ext

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import pub.gll.onepeas.libbase.di.http.result.BasicBean
import pub.gll.onepeas.libbase.di.http.result.HttpResult


/**
 * 加载网络
 * loadApi->真正请求网络
 * [onSuccess]->成功
 * [onFailure]->成功
 */
fun <T,R: BasicBean<T>> CoroutineScope.load(loadApi: suspend ()->R,
                                            onSuccess: suspend (data:T)->Unit,
                                            onFailure: suspend (code:Int,message:String?)->Unit,
){
    launch {
        flow {
            emit(loadApi.invoke())
        }.map {
            if (it.errorCode == 200) {
                if (it.data != null) {
                    HttpResult.Success(it.data!!)
                } else {
                    throw Exception("the result of remote's request is null")
                }
            } else {
                throw Exception(it.errorMsg)
            }
        }.onEach {
            onSuccess(it.result)
        }.catch {
            onFailure(-1,it.message)
        }.collect()
    }
}